package com.pump.common;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

public class ExcelUtil {
	
	public static Integer readIntCellValue(Sheet sheet,int row ,int cell)
	{
		Object obj = readCellValue(  sheet, row , cell);
		if(obj ==null)
		{
			return null;
		}
		if(obj instanceof Double )
		{
			return ((Double) obj).intValue();
		}
		return null;
	}
	
	public static Double readDoubleCellValue(Sheet sheet,int row ,int cell)
	{
		
		Object obj = readCellValue(  sheet, row , cell);
		if(obj ==null)
		{
			return null;
		}
		if(obj instanceof Double )
		{
			return (Double) obj;
		}
		return null;
	}
	
	public static String readStringCellValue(Sheet sheet,int row ,int cell)
	{
		Object obj = readCellValue(  sheet, row , cell);
		if(obj ==null)
		{
			return null;
		}
		if(obj instanceof String )
		{
			return (String) obj;
		}
		return null;
	}

	public static Object readCellValue(Sheet sheet,int rowIndex ,int cellIndex) {
		Row row = sheet.getRow(rowIndex);
		if(row ==null)
		{
			return null;
			
		}
		Cell cell = row.getCell(cellIndex);
		if(cell ==null)
		{
			return null;
		}
		
		int type = cell.getCellType();
		switch (type) {
		case Cell.CELL_TYPE_BLANK:
			return "";
		case Cell.CELL_TYPE_BOOLEAN:
			return cell.getBooleanCellValue();
		case Cell.CELL_TYPE_ERROR:
			return cell.getErrorCellValue();
		case Cell.CELL_TYPE_FORMULA:
			return getFormulaValue(cell);
		case Cell.CELL_TYPE_NUMERIC:
			return cell.getNumericCellValue();
		case Cell.CELL_TYPE_STRING:
			return cell.getStringCellValue();
		default:
			return null;

		}

	}

	private static Object getFormulaValue(Cell cell) {
		int type = cell.getCachedFormulaResultType();
		switch (type) {
		case Cell.CELL_TYPE_NUMERIC:return cell.getNumericCellValue();
		case Cell.CELL_TYPE_STRING:return cell.getStringCellValue();
		case Cell.CELL_TYPE_BOOLEAN:return cell.getBooleanCellValue();		
		case Cell.CELL_TYPE_ERROR:return cell.getErrorCellValue();
		}

		return null;
	}

}
